from django import http
from django.shortcuts import render
from django.views import View

from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from utils.response_code import RETCODE
from . import constants
from random import randint
from libs.yuntongxun.sms import CCP
#图形验证码
class ImageCodeView(View):
    def get(self, request, uuid):

        #接受前段UUID
        #生成图片 借助第三方包
        text, image_code = captcha.generate_captcha()
        #保存到数据库
        img_redis_client = get_redis_connection('verify_image_code')
        img_redis_client.setex('img_%s'%uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        #给前端返回数据
        return http.HttpResponse(image_code, content_type='image/jpeg')


#短信验证码
class SMSCodeView(View):
    def get(self,request,mobile):
        #接受三个参数 mobile   uuid   验证码
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')
        #验证图片验证码  获取  对比  删除
        img_redis_client = get_redis_connection('verify_image_code')
        redis_img_code = img_redis_client.get('img_%s' %uuid)
        if redis_img_code is None:
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效'})

        if redis_img_code.decode().lower() != image_code.lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码错误'})

        img_redis_client.delete('img_%s' %uuid)


        #获取随机6为数字短信验证码
        sms_code = '%06d' %randint(0,99999)
        #储存到数据库
        sms_redis_client = get_redis_connection('sms_code')
        sms_redis_client.setex('sms_%s' %mobile,constants.IMAGE_CODE_REDIS_EXPIRES,sms_code)
        send_fiag = sms_redis_client.get('send_fiag_%s' %mobile)

        if send_fiag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        p1 = sms_redis_client.pipeline()

        p1.setex('send_fiag_%s' %mobile,60,1)

        p1.setex('sms_%s' % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)

        p1.execute()
        #发送短信
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES],1)
        # print(sms_code)
        from celery_tasks.sms.tasks import ccp_send_sms_code
        ccp_send_sms_code.delay(mobile, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        print(sms_code)
        #返回相应对象
        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})

